package com.sharein.auth.business;

import java.util.Vector;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.sharein.auth.beans.User;
import com.sharein.db.Database;

import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
import javax.activation.*;

public abstract class UserManager {

	public static void signUpUser(User u, String question, String answer) {
		Object userValues[] = {u.getShareinID(), u.getPassword(), u.getEmail(), u.getFullname(), u.isMale()};
		String userFields[] = {"ShareinID", "Password", "Email", "Fullname", "Male"};
		Object statusValues[] = {u.getShareinID(), false, false, false};
		Object pwdrecoveryValues[] = {u.getShareinID(), question, answer};
		Database db = new Database();
		db.insert("User", userValues, userFields);
		db.insert("Status", statusValues, null);
		db.insert("Pwdrecovery", pwdrecoveryValues, null);
		db.closeConnextion();
	}
	
	public static void setUserSignedIn(String shareinID, boolean signedIn) {
		Database db = new Database();
		db.update("Status", new String[]{"SignedIn"}, new Object[]{signedIn}, "ShareinID", shareinID);
		db.closeConnextion();
	}
	
	public static void isUserOnline(String shareinID, boolean online) {
		Database db = new Database();
		db.update("Status", new String[]{"Online"}, new Object[]{online}, "ShareinID", shareinID);
		db.closeConnextion();
	}
	
	public static void isUserAway(String shareinID, boolean away) {
		Database db = new Database();
		db.update("Status", new String[]{"Away"}, new Object[]{away}, "ShareinID", shareinID);
		db.closeConnextion();
	}
	
	public static boolean isShareinID(String shareinID) {
		boolean isShareinID = false;
		String fields[] = {"ShareinID"};
		Database db = new Database();
		Object res[][] = db.select("User", "ShareinID", shareinID, fields);
		if(res.length > 0) isShareinID = true;
		db.closeConnextion();
		return isShareinID;
	}
	
	public static boolean isValidPassword(String shareinID, String password) {
		boolean isValidPassword = false;
		String fields[] = {"ShareinID", "Password"};
		Database db = new Database();
		Object res[][] = db.select("User", "ShareinID", shareinID, fields);
		if(res.length > 0) {
			for (Object[] objects : res) {
				if(objects[1].toString().equals(password)) isValidPassword = true;
			}
		}
		db.closeConnextion();
		return isValidPassword;
	}
	
	public static String getQuestion(String shareinID) {
		String fields[] = {"Question"};
		Database db = new Database();
		Object res[][] = db.select("Pwdrecovery", "ShareinID", shareinID, fields);
		db.closeConnextion();
		return res[0][0].toString();
	}
	
	public static String getAnswer(String shareinID) {
		String fields[] = {"Answer"};
		Database db = new Database();
		Object res[][] = db.select("Pwdrecovery", "ShareinID", shareinID, fields);
		db.closeConnextion();
		return res[0][0].toString();
	}
	
	public static User getUser(String shareinID) {
		Database db = new Database();
		Object res[][] = db.select("User", "ShareinID", shareinID, null);
		db.closeConnextion();
		boolean male;
		if(Integer.parseInt(res[0][4].toString()) == 1) male = true;
		else male = false;
		int age;
		if(res[0][5] != null) age = Integer.parseInt(res[0][5].toString());
		else age = -1;
		String location;
		if(res[0][6] != null) location = res[0][6].toString();
		else location = null;
		String photoID;
		if(res[0][7] != null) photoID = res[0][7].toString();
		else photoID = null;
		return new User(res[0][0].toString(), res[0][1].toString(), res[0][2].toString(), res[0][3].toString(), male, age, location, photoID);
	}
	
	public static User getSignedInUser(HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		String shareinID = null;
		if(cookies != null) {
			for (Cookie cookie : cookies) {
				if(cookie.getName().equals("shareinID")) shareinID = cookie.getValue();
			}
		}
		if(shareinID != null) return getUser(shareinID.toString());
		else {
			HttpSession session = request.getSession();
			Object shareinIDObj = session.getAttribute("shareinID");
			return (shareinIDObj == null)?null:getUser(shareinIDObj.toString());
		}
	}
	
	public static Vector<User> getUserFriends(String shareinID) {
		return null; 
	}
	
	public static void sendEmail(String host, String from, String password, String personal,
			String[] recipients, String subject, String[] bodys, String[] filesPaths) {
		class MyAuthenticator extends Authenticator {
			String username;
			String password;
			MyAuthenticator(String username, String password) {
				this.username = username;
				this.password = password;
			}
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(username, password);
			}
		}
		Properties props;
		Session mailSession;
		MimeMessage message;
		InternetAddress sender;
		Multipart mailBody;
		MimeBodyPart mainBody;
		MimeBodyPart mimeAttach;
		DataSource fds;
		
		//Creating a Session
		props=new Properties();
		props.put("mail.transport.protocol", "smtp");
		props.put("mail.smtp.host", host);
		props.put("mail.smtp.port", "25");
		props.put("mail.smtp.auth", "true");
		props.setProperty("mail.smtp.starttls.enable", "true");
		String username = from.substring(0, from.indexOf("@"));
		mailSession=Session.getDefaultInstance(props, new MyAuthenticator(username, password));
		
		//Constructing and Sending a Message
		try {
			
			//Starting a new Message
			message=new MimeMessage(mailSession);
			mailBody=new MimeMultipart();
			
			//Setting the Sender and Recipients
			if(personal != null) sender=new InternetAddress(from, personal);
			else sender=new InternetAddress(from);
			message.setFrom(sender);
			InternetAddress[] toList = new InternetAddress[recipients.length];
			for(int i=0; i<recipients.length; i++) toList[i] = new InternetAddress(recipients[i]);
			message.setRecipients(Message.RecipientType.TO, toList);
			
			//Setting the Subject and Headers
			message.setSubject(subject);
			
			//Setting the Message body
			for (String body : bodys) {
				mainBody=new MimeBodyPart();
				mainBody.setDataHandler(new DataHandler(body, "text/plain"));
				mailBody.addBodyPart(mainBody);
			}
			
			//Adding a single attachment
			if(filesPaths != null) {
				for (String filePath : filesPaths) {
					fds=new FileDataSource(filePath);
					mimeAttach=new MimeBodyPart();
					mimeAttach.setDataHandler(new DataHandler(fds));
					mimeAttach.setFileName(fds.getName());
					mailBody.addBodyPart(mimeAttach);
				}
			}
			
			//Sending email
			message.setContent(mailBody);
			Transport.send(message);
			System.out.println("Email sent.");
		}
		catch(java.io.UnsupportedEncodingException e) {
			System.out.println(e);
		}
		catch(MessagingException e) {
			System.out.println(e);
		}
		catch(IllegalStateException e) {
			System.out.println(e);
		}
	}
}
